package javax.core.storage.utils;

import org.springframework.util.DigestUtils;

import javax.core.common.utils.StringUtils;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class FileStorageUtil {
	public static final Map<String, String> mFileTypes = new HashMap<String, String>();

	static MessageDigest MD5 = null;

	static {
		// images
		mFileTypes.put("FFD8FF", "jpg");
		mFileTypes.put("89504E47", "png");
		mFileTypes.put("47494638", "gif");
		mFileTypes.put("49492A00", "tif");
		mFileTypes.put("424D", "bmp");
		// other files
		mFileTypes.put("41433130", "dwg"); // CAD
		mFileTypes.put("38425053", "psd");
		mFileTypes.put("7B5C727466", "rtf"); // 日记本
		mFileTypes.put("3C3F786D6C", "xml");
		mFileTypes.put("68746D6C3E", "html");
		mFileTypes.put("44656C69766572792D646174653A", "eml"); // 邮件
		mFileTypes.put("D0CF11E0", "doc");
		mFileTypes.put("5374616E64617264204A", "mdb");
		mFileTypes.put("252150532D41646F6265", "ps");
		mFileTypes.put("255044462D312E", "pdf");
		mFileTypes.put("504B0304", "docx");
		mFileTypes.put("52617221", "rar");
		mFileTypes.put("57415645", "wav");
		mFileTypes.put("41564920", "avi");
		mFileTypes.put("2E524D46", "rm");
		mFileTypes.put("000001BA", "mpg");
		mFileTypes.put("000001B3", "mpg");
		mFileTypes.put("6D6F6F76", "mov");
		mFileTypes.put("3026B2758E66CF11", "asf");
		mFileTypes.put("4D546864", "mid");
		mFileTypes.put("1F8B08", "gz");

		try {
			MD5 = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 对一个文件获取md5值字符串
	 */
	public static String getMD5(File file) {
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return getMD5(fileInputStream, true);
	}
	/**
	 * 对一个文件获取md5值字符串, 完成会关闭输入流
	 */
	public static String getMD5(InputStream fileInputStream, boolean closeStream) {
		if (fileInputStream == null) {
			return null;
		}
		try {
			return DigestUtils.md5DigestAsHex(fileInputStream);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (closeStream) {
				try {
					if (fileInputStream != null) {
						fileInputStream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 通过获取文件头的方式来获得文件的真正类型
	 */
	public static String getFileRealType(File file) {
		if (file == null) {
			return null;
		}
		try {
			return getFileRealType(new FileInputStream(file), true);
		} catch (FileNotFoundException e) {
			return null;
		}
	}

	/**
	 * 通过获取文件头的方式来获得文件的真正类型, 第二个参数表示结束后是否关闭流
	 */
	public static String getFileRealType(InputStream inputStream, boolean closeStream) {
		if (inputStream == null) {
			return null;
		}
		String value = null;
		byte[] b = new byte[4];
		try {
			inputStream.read(b, 0, b.length);
			value = bytesToHexString(b);
		} catch (IOException e) {
			value = null;
		} finally {
			if (closeStream) {
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return value;
	}

	/**
	 * 将要读取文件头信息的文件的byte数组转换成string类型表示
	 *
	 * @param src 要读取文件头信息的文件的byte数组
	 * @return 文件头信息
	 */
	private static String bytesToHexString(byte[] src) {
		StringBuilder builder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		String hv;
		for (int i = 0; i < src.length; i++) {
			// 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式，并转换为大写
			hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
			if (hv.length() < 2) {
				builder.append(0);
			}
			builder.append(hv);
		}
		return builder.toString();
	}

	/**
	 * 把文件存为MD5方式的路径, 例如一个名为test.jpg的文件, md5码为d3379f609e1aa88da2f50018d4fa218f <br/>
	 * 那么转换后的路径为: d33/79f/609/e1a/a88/da2/f50/018/d4f/a21/8f.jpg
	 *
	 * @param md5           文件的MD5编码
	 * @param fileShortName 不带路径的文件名
	 * @return 文件路径全名
	 */
	public static String toStoragePathByMD5(String md5, String fileShortName) {
		if (StringUtils.isEmpty(md5) || StringUtils.isEmpty(fileShortName) || md5.length() != 32) {
			return null;
		}
		// 获取文件扩展名
		String fileExtend = "";
		String[] splitedFile = fileShortName.split("\\.");
		if (splitedFile != null && splitedFile.length > 1) {
			fileExtend = splitedFile[splitedFile.length - 1];
		}

		String fullPathFileName = "";
		for (int i = 0; i < 11; i++) {
			if (i == 10) {
				fullPathFileName = fullPathFileName + md5.substring(3 * i, 3 * i + 2) + "." + fileExtend;
			} else {
				fullPathFileName = fullPathFileName + md5.substring(3 * i, 3 * i + 3) + "/";
			}
		}
		return fullPathFileName;
	}

	public static void closeInputStream(InputStream is) {
		if (is != null) {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
